<?php

require_once dirname(dirname(__FILE__)) . '/vendor/AliOssdkv2/aliyun.php';

use \Aliyun\OSS\OSSClient;

/**
 *
 * @author Ben <ben@xiaoman.cn>
 */
class AliyunUpload {

    /**
     * @var OssClient
     */
    private $ossClient;
    protected $https = true;
    protected $localFilePath;
    protected $bucket = '';
    protected $fileName;
    protected $fileKey;
    protected $setting;

    public function __construct() {
        $this->setting = new stdClass();
        $setting = Yii::app()->params['aliyun_oss'];
        $this->setting->end_point = $setting['end_point'];
        $this->setting->end_point_internal = $setting['end_point_internal'];
        $this->setting->access_key_id = $setting['access_key_id'];
        $this->setting->access_key_secret = $setting['access_key_secret'];
        $this->setting->default_bucket  = $setting['default_bucket'];

        $aliyunOss = $this->setting;
        $this->ossClient = OSSClient::factory(array(
                    'Endpoint' => (Yii::app()->params['env'] == 'production') ? $aliyunOss->end_point_internal : $aliyunOss->end_point,
                    'AccessKeyId' => $aliyunOss->access_key_id,
                    'AccessKeySecret' => $aliyunOss->access_key_secret,
        ));
        $this->setBucket($aliyunOss->default_bucket);
    }

    /**
     * @return mixed
     */
    public function getBucket() {
        return $this->bucket;
    }

    /**
     * @param mixed $bucket
     */
    public function setBucket($bucket) {
        $this->bucket = $bucket;
    }

    /**
     * @return mixed
     */
    public function getFileName() {
        return $this->fileName;
    }

    /**
     * @param mixed $fileName
     */
    public function setFileName($fileName) {
        $this->fileName = $fileName;
    }

    /**
     * @return mixed
     */
    public function getFileKey() {
        $extName = strtolower(strrchr($this->fileKey, '.'));
        if (!$extName) {
            $extName = strtolower(strrchr($this->fileName, '.'));
            $this->fileKey .= $extName;
        }
        return $this->fileKey;
    }

    /**
     * @param mixed $fileKey
     */
    public function setFileKey($fileKey) {
        $this->fileKey = $fileKey;
    }

    /**
     * @return mixed
     */
    public function getLocalFilePath() {
        return $this->localFilePath;
    }

    /**
     * @param mixed $localFilePath
     */
    public function setLocalFilePath($localFilePath) {
        $this->localFilePath = $localFilePath;
    }

    public function getFileExt() {
        $ext = strtolower(strrchr($this->getFileName(), '.'));
        if (empty($ext)) {
            $ext = strtolower(strrchr($this->getLocalFilePath(), '.'));
        }
        return $ext;
    }

    public function getFileMimeType() {
        $fileName = $this->getLocalFilePath();

        if (empty($fileName)) {
            return '';
        }

        $fileInfo = new \finfo(FILEINFO_MIME);
        $fileType = $fileInfo->file($fileName);
        if ($fileType == false) {
            return '';
        }
        $tmp = explode(";", $fileType);
        return $tmp[0];
    }

    public function isHttps() {
        return $this->https;
    }

    public function getFileUrl() {
        $info = parse_url($this->setting->end_point);
        return 'http' . ($this->isHttps() ? 's' : '') . '://' . $this->getBucket() . '.' . $info['host'] . '/' . $this->getFileKey();
    }

    public function upload($content = null) {
        try {
            $size = $content ? strlen($content) : filesize($this->getLocalFilePath());
            $options = array(
                'ContentType' => $this->getFileMimeType(),
                'Bucket' => $this->getBucket(),
                'Key' => $this->getFileKey(),
                'Content' => $content ? $content : fopen($this->getLocalFilePath(), 'r'),
                'ContentLength' => $size,
                'ContentDisposition' => 'attachment; filename="' . rawurlencode($this->getFileName()) . '"',
            );

            $this->ossClient->putObject($options);
        } catch (Exception $e) {

            throw $e;
        }
        return true;
    }

    public function uploadByBase64($code) {
        if (strlen($code) < 10) {
            return;
        }
        $pos = strpos($code, ',');
        $type = explode(':', explode(';', substr($code, 0, $pos + 1))[0])[1];
        $data = substr($code, $pos + 1);

        $filekey = 'from_base64_' . md5(microtime(true)) . mt_rand(1000, 9999);
        switch ($type) {
            case 'image/png':
                $ext = '.png';
                break;
        }
        $filename = $filekey . $ext;
        $this->setFileName($filename);
        $this->setFileKey($filekey);
        $localFilePath = sys_get_temp_dir() . '/' . $filename;
        file_put_contents($localFilePath, base64_decode($data));

        $this->setLocalFilePath($localFilePath);
        $this->upload();
        @unlink($localFilePath);
    }

}
